<template>
  <div>
    <!-- 添加检查卡 -->
    <el-collapse v-model="activeNames">
      <el-collapse-item
        v-for="(item, index) in tableData"
        :key="index"
        :name="String(index + 1)"
      >
        <template #title>
          <div class="w-full flex justify-between items-center pr-2">
            <span
              >检查卡
              <span v-if="tableData && tableData.length > 1">
                {{ index + 1 }}
              </span>
            </span>
            <el-button type="danger" @click="delClanBtn(index)">删除</el-button>
          </div>
        </template>

        <el-form
          :model="item"
          :ref="(el) => (checkRef[index] = el)"
          :rules="rules[index]"
        >
          <el-descriptions border :column="3">
            <el-descriptions-item label="姓名" align="center">
              <el-form-item prop="name" class="m-0">
                <el-input v-model="item.name" placeholder="请输入姓名" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="联系方式" align="center">
              <el-form-item prop="phone" class="m-0">
                <el-input v-model="item.phone" placeholder="请输入联系方式" />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="出生日期" align="center">
              <el-form-item label="" prop="birthday" class="m-0">
                <el-date-picker
                  v-model="item.birthday"
                  type="datetime"
                  placeholder="请选择出生日期"
                  format="YYYY-MM-DD"
                  value-format="x"
                  :disabled-date="disabledDateStart"
                  class="w-full"
                />
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="检查卡关系" align="center">
              <el-form-item prop="baseRelationId" class="m-0">
                <el-select
                  v-model="item.baseRelationId"
                  placeholder="请选择检查卡关系"
                  filterable
                >
                  <el-option
                    v-for="i in props.baseList"
                    :key="i.id"
                    :label="i.name"
                    :value="i.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="职业" align="center">
              <el-form-item prop="occupationName" class="m-0">
                <el-select
                  v-model="item.occupationName"
                  placeholder="请选择职业"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="i in props.occupationList"
                    :key="i.id"
                    :label="i.name"
                    :value="i.name"
                  />
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="工作环境" align="center">
              <el-form-item prop="workEnvName" class="m-0">
                <el-select
                  v-model="item.workEnvName"
                  placeholder="请选择工作环境"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="i in props.workEnvList"
                    :key="i.id"
                    :label="i.name"
                    :value="i.name"
                  />
                </el-select>
              </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="用眼距离" align="center">
              <el-form-item prop="eyeUsageDistanceName" class="m-0">
                <el-select
                  v-model="item.eyeUsageDistanceName"
                  placeholder="请选择用眼距离"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="i in props.eyeDistanceList"
                    :key="i.id"
                    :label="i.name"
                    :value="i.name"
                  />
                </el-select>
              </el-form-item>
            </el-descriptions-item>
          </el-descriptions>
        </el-form>
      </el-collapse-item>
    </el-collapse>
    <el-button
      type="primary"
      icon="Plus"
      class="w-full mt-2"
      @click="add_one_check"
      >添加</el-button
    >
  </div>
</template>

<script setup>
import { ref, onMounted, watchEffect } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";
import { handleApiResponse } from "@/utils/request.js";
import { CreateRelative } from "../../../../../wailsjs/go/api/CustomerApi";

onMounted(() => {});

const emit = defineEmits("handleBack");
const props = defineProps({
  checkForm: {
    type: Object,
    default: () => {},
  },
  baseList: {
    type: Array,
    default: () => [],
  },
  workEnvList: {
    type: Array,
    default: () => [],
  },
  occupationList: {
    type: Array,
    default: () => [],
  },
  eyeDistanceList: {
    type: Array,
    default: () => [],
  },
});

const activeNames = ref(["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]);

const checkRef = ref([]);
const tableData = ref([
  {
    name: "",
    sex: "",
    birthday: "",
    baseRelationId: null,
    customerId: null,
  },
]);

const rules = ref([]);

const add_one_check = () => {
  if (tableData.value.length >= 10) {
    ElMessage({
      message: "最多添加10个检查卡",
      type: "error",
    });
    return;
  }
  tableData.value.push({
    name: "",
    sex: "",
    birthday: "",
    baseRelationId: null,
    customerId: null,
  });
};
const delClanBtn = (index) => {
  tableData.value.splice(index, 1);
};

// 提交
const handleSubmit = async () => {
  const validationPromises = checkRef.value.filter(Boolean).map(
    (formRef) =>
      new Promise((resolve) => {
        formRef.validate((valid) => resolve(valid));
      })
  );
  const allValidations = await Promise.all(validationPromises);
  const isValid = allValidations.every((result) => result);
  if (!isValid) return;

  emit("handleBack", 1);

  let list = cloneDeep(tableData.value);
  list.forEach((item) => {
    item.customerId = props.checkForm.id;
    // item.birthday = item.birthday / 1000;
  });

  handleApiResponse(() => CreateRelative({ relatives: list, organId: 0 })).then(
    (res) => {
      if (res.code == 0) {
        ElMessage.success("添加成功");
      }
      emit("handleBack");
    }
  );
};
// 判断所选时间对比
const disabledDateStart = (time) => {
  return time.getTime() > Date.now();
};

watchEffect(() => {
  //   checkRef.value = new Array(tableData.value.length).fill(null);
  rules.value = new Array(tableData.value.length).fill({
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" },
      {
        min: 2,
        message: "最小为2个字符",
        trigger: "blur",
      },
    ],
    // sex: [{ required: true, message: "性别不能为空", trigger: "change" }],
    phone: [
      { required: true, message: "电话号码不能为空", trigger: "blur" },
      { min: 11, max: 11, message: "长度为11位", trigger: "blur" },
    ],
    birthday: [
      { required: true, message: "出生日期不能为空", trigger: "change" },
    ],
    baseRelationId: [
      { required: true, message: "检查卡关系不能为空", trigger: "change" },
    ],
  });
});

defineExpose({
  handleSubmit,
});
</script>

<style scoped lang="scss">
</style>